package com.jvup.gameshow.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;

import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jvup.common.support.base.BaseActivity;
import com.jvup.common.constant.Navigation;
import com.jvup.gameshow.R;
import com.jvup.gameshow.controller.ImagePickerController;
import com.jvup.gameshow.databinding.ActivityImagePickerBinding;
import com.jvup.gameshow.model.entity.ImageFloder;
import com.jvup.gameshow.model.viewModel.impl.ImagePickerViewModel;
import com.jvup.gameshow.model.viewModel.impl.ImagePickerViewModel.AlbumListItemModel;
import com.jvup.gameshow.utils.ContentResolverUtils;
import com.qire.antsbinder.viewModel.ViewModelFactory;
import com.qire.antscore.annotation.RouteMapping;
import com.qire.antsrouter.inject.Autowired;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;
import pub.devrel.easypermissions.EasyPermissions.PermissionCallbacks;

/**
 * 图片选择
 */
@RouteMapping(path = Navigation.Page.ImagePickerPage)
public class ImagePickerActivity extends BaseActivity<ActivityImagePickerBinding> implements PermissionCallbacks {

    public static final int CAMERA_REQUEST_CODE = 1;

    ImagePickerViewModel viewModel;
    ImagePickerController controller;

    @Autowired
    PickerImageListener pickerImageListener;
    @Autowired
    int maxCount = 9;

    @Override
    public int layoutRid() {
        return R.layout.activity_image_picker;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        viewModel = ViewModelFactory.crate(this,ImagePickerViewModel.class);
        viewModel.setMaxLimit(maxCount);
        controller = new ImagePickerController(this);
        controller.bindViewModel(viewModel);

        ActivityImagePickerBinding viewDataBinder = viewDataBinder();
        viewDataBinder.setImagePickerViewModel(viewModel);
        viewDataBinder.setImagePickerController(controller);

        if(checkPermission()) {
            initData();
            initListener();
        }
    }


    private void initData(){

        viewModel.updateChooseHintText();

        viewModel.imageAll.setDir("/所有图片");
        viewModel.mDirPaths.add(viewModel.imageAll);
        ContentResolverUtils.queryImages(this, viewModel.imageAll, viewModel.mDirPaths);

        viewModel.setCurrentImageFolder(viewModel.imageAll);

        int dirPathsSize = viewModel.mDirPaths.size();
        for(int index=0;index < dirPathsSize; index++ ){
            ImageFloder floder = viewModel.mDirPaths.get(index);
            String titleName = floder.getName() + " (" + floder.images.size() + ")";
            int bottomLineShow = index != dirPathsSize - 1 ? View.VISIBLE : View.GONE;
            int chooseShow = viewModel.getCurrentImageFolder() == floder ? View.VISIBLE : View.GONE;

            viewModel.folderDataList.add(new AlbumListItemModel("file://" + floder.getFirstImagePath(),titleName,bottomLineShow,chooseShow));
        }

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        viewDataBinder().picSelectRv.setLayoutManager(linearLayoutManager);

        viewModel.folderAdapter.notifyDataSetChanged();
        viewModel.selectAdapter.notifyDataSetChanged();
    }

    private void initListener() {

        ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;//删除
                int swipeFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;//拖拽改变顺序
                return makeMovementFlags(swipeFlags, dragFlags);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                Collections.swap(viewModel.selectDataList, viewHolder.getAdapterPosition(), target.getAdapterPosition());
                viewModel.selectAdapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                viewModel.removeSelectBitmapItem(viewHolder.getAdapterPosition());
            }

            @Override
            public boolean isLongPressDragEnabled() {
                return true;
            }
        });
        helper.attachToRecyclerView(viewDataBinder().picSelectRv);

    }

    private boolean checkPermission(){
        if (!EasyPermissions.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            EasyPermissions.requestPermissions(this, "需要允许访问相册的权限", CAMERA_REQUEST_CODE, Manifest.permission.READ_EXTERNAL_STORAGE);
            return false;
        }else{
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        initData();
        initListener();
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        Dialog dialog = new AlertDialog.Builder(this)
                .setTitle("手动设置权限")
                .setMessage(String.format("上传照片需要访问相册，请点击打开->找到%s->权限->分别允许存储及相机权限",getResources().getString(R.string.app_name)))
                .setPositiveButton("打开", (dialog2, which) ->startActivity(new Intent(Settings.ACTION_APPLICATION_SETTINGS)))
                .setNegativeButton("关闭", (dialog3, which) -> dialog3.dismiss())
                .create();
        dialog.show();
    }

    public void notifyResultsToParent(ArrayList<String> pickerPathList){
        if(pickerImageListener != null) {
            pickerImageListener.onPickerImage(pickerPathList);
        }
        finish();
    }

    /**
     * 选择图片监听器
     */
    public interface PickerImageListener {
        void onPickerImage(ArrayList<String> pickerPathList);
    }
}
